package ldh.im.socket;

import ldh.im.ClientChannelService;
import ldh.im.dto.base.SuccessResp;
import ldh.im.dto.business.ExitReq;
import ldh.im.dto.business.LoginReq;
import ldh.im.dto.business.LoginResp;
import ldh.im.dto.business.P2pTextMessage;
import ldh.im.exception.ImServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicLong;

public class ClientDemo {

    private static final Logger LOGGER = LoggerFactory.getLogger(ClientDemo.class);

    public static void main(String[] args) throws Exception {
        LOGGER.debug("start demo");
        AtomicLong seq = new AtomicLong(1000);
        for(int i=0; i<200; i++) {
            String userName = "test00" + i;
            new Thread(()->{
                try {
                    sendMessage(userName, 1000, seq);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }

    private static void sendMessage(String userName, int count, AtomicLong seq) throws InterruptedException, TimeoutException, ImServiceException, ExecutionException {
        ClientChannelService clientService = new ClientChannelService("localhost", 9090, (dto)->{});
        clientService.connection();

        LoginReq loginReqTo = new LoginReq();
        loginReqTo.setUserName(userName);
        loginReqTo.setPassword(userName.toCharArray());
        loginReqTo.setLocalSeq("1");
        loginReqTo.setCreateDateTime(LocalDateTime.now());

        LoginResp loginRec = (LoginResp) clientService.write(loginReqTo).get();

        clientService.setAuthToken(loginRec.getAuthToken(), loginRec.getAuthCode());

        long startTime = System.currentTimeMillis();
        for(int i=0; i<count; i++) {
            P2pTextMessage textMessage = new P2pTextMessage();
            textMessage.setMessage("hello world");
            textMessage.setToUserId(2222L);
            textMessage.setFromUserId(1111L);
            textMessage.setLocalSeq(seq.incrementAndGet() + "");
            SuccessResp rec = (SuccessResp)  clientService.write(textMessage).get();
            LOGGER.debug("成功返回：" + rec.getLocalSeq());
        }
        long time = System.currentTimeMillis() - startTime;
        System.out.println("time:" + time);
        ExitReq exitReq = new ExitReq();
        exitReq.setLocalSeq("2");
        SuccessResp rec = (SuccessResp)clientService.write(exitReq).get();
        LOGGER.debug("成功退出：" + rec.getLocalSeq());
        clientService.closeFuture().sync();
        clientService.close();
        System.out.println("client exitReq!!!!");
    }
}
